<template>
  <div>
    <!-- 面包导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" plain @click="adddialogFormVisible = true">添加权限</el-button>
        </el-col>
      </el-row>
      <!-- 数据列表区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 扩展列 -->
        <el-table-column align="center" type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="index1"
              :class="['bdBottom',index1===0?'bdTop':'','vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRole(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="index2"
                  :class="[index2===0?'':'bdTop','vcenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRole(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRole(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色管理"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              plain
              type="success"
              icon="el-icon-edit"
              @click="editForm(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              plain
              type="warning"
              icon="el-icon-delete"
              @click="removeRoleList(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              plain
              type="danger"
              icon="el-icon-setting"
              @click="settingRoles(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加权限的对话框 -->
    <el-dialog title="添加角色" :visible.sync="adddialogFormVisible" width="30%">
      <el-form :model="addRoleList" :rules="addRoleRule" ref="addroleRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSure">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editdialogFormVisible" width="30%">
      <el-form label-width="80px" :model="editRoleList">
        <el-form-item label="角色ID">
          <el-input v-model="editRoleList.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editRoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="提示" :visible.sync="settingsDialogVisible" width="30%" @close="removeKey">
      <!-- default-expand-all是用来让树形组件默认展开所有 -->
      <!-- show-checkbox是让属性组件之前添加一个可选择的效果 -->
      <!-- prop属性使用来指定内部展示数据 label是指定被展示数据名称 -->
      <!-- data是用来指定数据源 -->
      <el-tree
        show-checkbox
        :data="addSetting"
        node-key="id"
        :props="treeProps"
        default-expand-all
        :default-checked-keys="rightsKeyArr"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="settingsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Role',
  data() {
    return {
      // 编辑用户数据列表
      editRoleList: [],
      editRoleArr: {
        roleId: 0,
        roleName: '',
        roleDesc: ''
      },
      rolesList: [],
      // 用来展示添加角色列表
      addRoleList: {
        roleName: '',
        roleDesc: ''
      },
      // 控制的是添加权限的弹框是否可见
      adddialogFormVisible: false,
      // 控制设置权限弹框的可见性
      settingsDialogVisible: false,
      // 控制编辑用户权限弹框的可见性
      editdialogFormVisible: false,
      addRoleRule: {
        roleName: [],
        roleDesc: []
      },
      // 这是添加权限展示用的数据
      addSetting: [],
      // 用来存储默认勾选三级权限的ID的数组
      rightsKeyArr: [],
      // 这是用来展示树形结构的数据
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 用来存储展示tree中的所有Id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 分配权限
    async addTree() {
      // 存储的是全选中状态,合半选中状态
      // 获取所有分支的选中状态
      // 之后拼接成一个数组
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const keyStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keyStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.settingsDialogVisible = false
      this.getRolesList()
    },

    // 当关闭的时候清空获取权限的缓存
    removeKey() {
      this.rightsKeyArr = []
    },

    // 删除用户列表数据
    async removeRoleList(id) {
      const config = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (config !== 'confirm') {
        return this.$message.info('用户取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.info(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },

    // 编辑用户列表获取数据
    async editForm(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.data.msg)
      }
      this.editRoleList = res.data
      this.editdialogFormVisible = true
    },

    // 编辑提交用户列表数据
    async editAddForm() {
      const { data: res } = await this.$http.put(`roles/${this.editRoleList.roleId}`, {
        roleName: this.editRoleList.roleName,
        roleDesc: this.editRoleList.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getRolesList()
      this.editdialogFormVisible = false
    },

    // 用来获取到三级分支的id
    // node指代需要递归的数据，实际上就是指scope.row
    // arr指代id将要保存到的地方，实际上指代的是dafault-checked-keys 对应的属性值rightsKeyArr
    getLeafKey(node, arr) {
      // 判断是否具有children属性来判断他是否是三级分支
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级节点，就表示是一级二级节点还要继续获取
      node.children.forEach(item => {
        this.getLeafKey(item, arr)
      })
    },

    // 点击设置时的操作
    async settingRoles(roles) {
      this.roleId = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.addSetting = res.data
      this.getLeafKey(roles, this.rightsKeyArr)
      this.settingsDialogVisible = true
    },

    // 当点击x号删除时操作
    async removeRole(role, rightId) {
      const removeRoles = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(removeRoles)
      if (removeRoles !== 'confirm') {
        return this.$message.info('用户取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 将role的资源数赋值给data用来进行局部更新
      role.children = res.data
    },

    // 点击确定按钮来添加用户时
    async addRoleSure() {
      const { data: res } = await this.$http.post('roles', this.addRoleList)
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg)
      }
      this.getRolesList()
      this.adddialogFormVisible = false
      this.$refs.addroleRef.resetFields()
    },

    // 获取用户权限信息
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        res.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #ccc;
}
.bdBottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
